from django.shortcuts import render, HttpResponse
# 导入类
from userweb.models import Menu, Permission,Role
from django.http import JsonResponse
import json


def index(request):
    return render(request, 'user/permission.html')


def list_values(request):
    """获取所有的权限数据----以菜单的结构展开"""

    #  获取所有菜单
    menu_objs = list(Menu.objects.all().values())
    #  获取所有的权限条目
    permission_objs = list(Permission.objects.all().values())

    # ===== 组合成树状数据===
    data = []
    # 遍历
    for item in menu_objs:
        # 定义一个临时的temp_dict
        temp_dict = {}
        # 添加
        temp_dict['title'] = item.get('title')
        temp_dict['id'] = item.get('id')
        temp_dict['spread'] = True
        temp_dict['children'] = []
        # 遍历权限，把属于这个顶级菜单的权限放进去
        for val in permission_objs:
            if val['menu_id'] == item['id']:
                temp_dict['children'].append({'title': val.get('title'), 'id': val.get('order')})
        # 附加
        data.append(temp_dict)
    # 返回
    return JsonResponse({'data': data})


def get_permission_by_order(request):
    # 根据order值获取当前的权限明细
    order = request.POST.get('order')
    # 获取具体数据
    objs = list(Permission.objects.filter(order=order).values())
    # 返回
    return JsonResponse({'data': objs[0]})


def get_permission_by_role(request):
    """通过角色获取相应角色权限"""
    # 获取当前的角色
    role_id = request.POST.get('role_id')

    # 获取当前的权限 -- manytomany字段的查询
    role_obj = Role.objects.filter(id=role_id).first()
    permisson_objs = list(role_obj.permission_set.all().values())

    # 整理数据
    data = []
    # 遍历
    for item in permisson_objs:
        data.append(item.get('order'))

    return JsonResponse({'data': data})


def add_value(request):
    # 获取传递的数据
    rec = request.POST
    # 定义返回值类型
    res = {'status': True}
    # 异常处理
    try:
        Permission.objects.create(title=rec.get('title'), order=rec.get('order'), menu_id=rec.get('menu_id'),
                                  url=rec.get('url'))

    except Exception as e:
        res['status'] = False
        res['error'] = "添加权限出现异常！具体原因：" + str(e)

    return JsonResponse(res)


def edit_value(request):
    # 获取传递的数据
    rec = request.POST
    # 定义返回值类型
    res = {'status': True}
    # 异常处理
    try:
        # 获取当前的权限条目
        obj = Permission.objects.get(id=rec.get('id'))
        obj.url = rec.get('url')
        obj.menu_id = rec.get('menu_id')
        obj.title = rec.get('title')
        obj.order = rec.get('order')
        obj.save()

    except Exception as e:
        res['status'] = False
        res['error'] = "修改权限出现异常！具体原因：" + str(e)

    return JsonResponse(res)


def del_value(request):
    # 接收后台传递的Id
    id = request.POST.get('id')
    # 定义返回的数据
    res = {'status': True}
    # 异常处理
    try:
        Permission.objects.get(id=id).delete()
    except Exception as e:
        res['status'] = False
        res['error'] = "删除权限出现异常！具体原因：" + str(e)

    return JsonResponse(res)


